
#include "mainwindow.h"
#include "dialog/routeadddialog.h"
#include "textdialog.h"
#include "ui_mainwindow.h"
#include "utils/scripts.h"
#include "widgets/routeitemwidget.h"

#include <QClipboard>
#include <QKeyEvent>
#include <QMessageBox>
#include <QProcess>
#include <qrcutil.h>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
  , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->splitter->setSizes(QList<int>() << 1000 << 50);

    on_btn_refresh_clicked();
}
MainWindow::~MainWindow()
{

}

QString MainWindow::modify_metric(const QString &var, int metric)
{
    auto list = var.trimmed().split(" ");
    list.removeLast();
    list.append(QString::number(metric));

    return list.join(" ");
}

void MainWindow::on_btn_refresh_clicked()
{
    ui->list_ip_route->clear();

    QProcess process;
    process.start("ip", QStringList() << "route");
    process.waitForFinished();

    QString output = process.readAllStandardOutput();
    foreach (QString var, output.split("\n")) {
        // if (var.startsWith("default")) {
        if (!var.trimmed().isEmpty()) {
            QListWidgetItem *item = new QListWidgetItem;
            RouteItemWidget *item_widget = RouteItemWidget::make(var);
            item->setSizeHint(item_widget->sizeHint());
            ui->list_ip_route->addItem(item);
            ui->list_ip_route->setItemWidget(item, item_widget);
            connect(item_widget, &RouteItemWidget::onDelete, this, &MainWindow::slot_route_deleted);
            connect(item_widget, &RouteItemWidget::onRestoreDelete, this, &MainWindow::slot_route_restore_deleted);
            connect(item_widget, &RouteItemWidget::applySignal, this, &MainWindow::slot_route_apply_signal);
        }
    };
}

void MainWindow::on_list_ip_route_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    if (!current) return;
    auto item_widget = qobject_cast<RouteItemWidget*>(ui->list_ip_route->itemWidget(current));
    if (item_widget) {
        ui->statusbar->showMessage(item_widget->route());
    }
}


void MainWindow::on_btn_ok_clicked()
{
    QStringList list;

    // del
    for (int index = 0; index < ui->list_ip_route->count(); ++index) {
        auto item = ui->list_ip_route->item(index);
        auto item_widget = ui->list_ip_route->itemWidget(item);
        auto route_widget = qobject_cast<RouteItemWidget*>(item_widget);
        list << route_widget->script_del();
    }

    // add
    QStringList defaultList;
    for (int index = 0; index < ui->list_ip_route->count(); ++index) {
        auto item = ui->list_ip_route->item(index);
        auto item_widget = ui->list_ip_route->itemWidget(item);
        auto route_widget = qobject_cast<RouteItemWidget*>(item_widget);
        if (route_widget->isEnabled()) {
            if (route_widget->script_add().contains("default")) {
                defaultList << route_widget->script_add();
            } else {
                list << route_widget->script_add();
            }
        }
    }
    list << defaultList;

    TextDialog dialog;
    dialog.setText(list.join("\n"));
    if (dialog.exec() == QDialog::Accepted) {
        // 1. 编辑脚本
        auto var = QString(list.join("\n") + "\n").toUtf8();
        auto filename = make_tempfile(var);
        // qApp->clipboard()->setText("sudo bash '" + tempfile.fileName() +"'");

        // 2. 执行脚本
        QProcess process;
        process.start("pkexec", QStringList() << "bash" << filename);
        process.waitForFinished();

        // 3. 重新加载
        on_btn_refresh_clicked();
    }
}

void MainWindow::slot_route_deleted(RouteItemWidget *route_widget)
{
    auto item_widget = qobject_cast<RouteItemWidget*>(sender());
    if (item_widget) {
        QProcess process;
        process.start("pkexec ip route del " + item_widget->route());
        process.waitForFinished();
    }
}

void MainWindow::slot_route_restore_deleted(RouteItemWidget *route_widget)
{
    auto item_widget = qobject_cast<RouteItemWidget*>(sender());
    if (item_widget) {
        QProcess process;
        process.start("pkexec ip route add " + item_widget->route());
        process.waitForFinished();
    }
}

void MainWindow::slot_route_apply_signal(RouteItemWidget *route_widget)
{
    auto item_widget = qobject_cast<RouteItemWidget*>(sender());
    if (item_widget) {
        QProcess process;
        process.start("pkexec", QStringList() << "bash" << make_tempfile(route_widget->scripts()));
        process.waitForFinished();
        on_btn_refresh_clicked();
    }
}

QString MainWindow::make_tempfile(QString var)
{
    auto tempfile = new QTemporaryFile(this);
    tempfile->open();
    tempfile->write(var.toUtf8());
    tempfile->flush();
    tempfile->close();
    return tempfile->fileName();
}

void MainWindow::make_scripts(QString var)
{
    qApp->clipboard()->setText("sudo bash '" + make_tempfile(var) +"'");
}

void MainWindow::copy_script()
{
    auto item = ui->list_ip_route->currentItem();
    if (item) {
        auto item_widget = qobject_cast<RouteItemWidget*>(ui->list_ip_route->itemWidget(item));
        if (item_widget) make_scripts(item_widget->scripts());
    }
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->modifiers() == Qt::Modifier::CTRL && event->key() == Qt::Key_C) {
        copy_script();
    }
}

void MainWindow::on_action_add_route_triggered()
{
    // sudo ip r add 192.168.2.0/24 via 192.168.23.1 dev eno1
    RouteAddDialog dialog;
    if (dialog.exec() == QDialog::Accepted) {
        ui->statusbar->showMessage(dialog.route());
        Scripts::bash_scripts("pkexec ip route add " + dialog.route());
    }

}
